import { defineStore } from 'pinia';
import { UserAuthorizeInfo } from '../../types/User';

const PEEKPAJOB_CMS_USER = 'PeekpaJobCMSUser';

// 定义 UserStore
const userStore = defineStore('User', {
  // state 定义
  state: (): UserAuthorizeInfo => {
    const localData = localStorage.getItem(PEEKPAJOB_CMS_USER);
    const defaultValue: UserAuthorizeInfo = {
      id: '',
      name: '',
      token: '',
      avatar: '',
    };
    return localData ? JSON.parse(localData) : defaultValue;
  },
  getters: {
    // 获取用户名
    getName(stage: UserAuthorizeInfo): string {
      return stage.name;
    },
    // 获取用户token
    getToken(stage: UserAuthorizeInfo): string {
      return stage.token;
    },
    // 获取用户头像
    getAvatar(stage: UserAuthorizeInfo): string {
      return stage.avatar;
    },
  },
  actions: {
    // 判断是否有用户登录信息
    isLogin(): boolean {
      return this.token !== '';
    },
    // 存储/更新用户信息
    setUser(userData: UserAuthorizeInfo): void {
      this.id = userData.id;
      this.name = userData.name;
      this.token = userData.token;
      this.avatar = userData.avatar;
      localStorage.setItem(PEEKPAJOB_CMS_USER, JSON.stringify(userData));
    },
    // 登出
    logout() {
      localStorage.removeItem(PEEKPAJOB_CMS_USER);
      this.id = '';
      this.token = '';
      this.name = '';
      this.avatar = '';
    },
  },
});

export default userStore;
